import { PageHeader } from 'antd';
import { Button, Form, Input, message, Upload, Switch, Space, Table, Modal } from 'antd';
import './index.scss'
import { useNavigate, useLocation } from 'react-router-dom';
import { PlusOutlined, LoadingOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import format from '../../../../../utils/formatDay_ssh'
import { mod } from '../../../../../api/member_interests_ssh'
const Mod_memberinterests = () => {

    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState();
    const location = useLocation()
    const [form1] = Form.useForm()
    const [fileName, setFileName] = useState()
    const [data, setData] = useState([])
    const urlImg = 'http://192.168.221.241:8005/'
    useEffect(() => {
        console.log(location.state.equityPicture, 123);
        if (location.state.equityPicture) {
            console.log(urlImg + location.state.equityPicture, 1234);
            setImageUrl(urlImg + location.state.equityPicture)
        }
        let formData = location.state
        delete formData.equityPicture
        form1.setFieldsValue(formData)
        setData(location.state.equityRulesList)

    }, [])
    const columns = [
        {
            title: '规则名称',
            dataIndex: 'equityRulesName',
            key: 'equityRulesName',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '折扣率',
            dataIndex: 'equityDiscount',
            key: 'equityDiscount',
        },
        {
            title: '最后修改时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
        },

    ];
    const routes = [
        {
            path: 'index',
            breadcrumbName: '用户管理',
        },
        {
            path: 'first',
            breadcrumbName: '会员权益',
        },
        {
            path: 'second',
            breadcrumbName: '编辑系统自带权益',
        },
    ];

    const Navigate = useNavigate()
    const onFinish = () => {
        console.log('Success:', form1.getFieldValue());
        let _from1 = form1.getFieldValue()
        delete _from1.equityDiscount
        delete _from1.equityRulesList
        delete _from1.equityRulesName
        delete _from1.equityUpdateTime
        delete _from1.updateTime
        _from1.equityPicture = fileName
        console.log(_from1);
        mod(_from1).then((res) => {
            console.log(res);
            setTimeout(() => {
                Navigate('/home/user/member-interests')
            }, 500);
        })
    };
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };
    const goback = () => {
        Navigate('/home/user/member-interests')
    }
    const getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    };

    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }

        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }

        return isJpgOrPng && isLt2M;
    };

    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }

        if (info.file.status === 'done') {
            console.log(info.file);
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, (url) => {
                setLoading(false);
                // setImageUrl(url);
                setImageUrl(url);
                setFileName(info.file.response.fileName)

                console.log(info.file.response.fileName);
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                Upload
            </div>
        </div>
    );
    return <div className='Mod_memberinterests'>
        <PageHeader
            className="site-page-header"
            title="编辑系统自带权益"
            breadcrumb={{
                routes,
            }}

        />
        <div className='content_editor clear' >
            <div className='left'>
                <Form
                    form={form1}
                    name="basic"
                    labelCol={{
                        span: 6,
                    }}
                    wrapperCol={{
                        span: 10,
                    }}

                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        label="权益名称"
                        name="equityName"
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="权益说明"
                        name="equityNote"
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="上传图标"
                        name="equityPicture"
                        valuePropName="fileList"
                        getValueFromEvent={e => {
                            if (Array.isArray(e)) {
                                return e;
                            }
                            return e && e.fileList
                        }}

                    >
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="http://192.168.221.241:8005/service_setting/fileRelevant/fileUpload"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}

                        >
                            {imageUrl ? (
                                <img
                                    src={imageUrl}
                                    alt="avatar"
                                    style={{
                                        width: '100%',
                                    }}
                                />
                            ) : (
                                uploadButton
                            )}
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        label="权益类型"
                        name="equityType"
                    >
                        <Input />
                    </Form.Item>
                    <div className='btmm'>
                        <Table rowKey={(record) => record.equityId} columns={columns} dataSource={data} pagination={false} />
                        <Button type="primary" htmlType="submit">
                            提交
                        </Button>
                        &nbsp; &nbsp; &nbsp;
                        <Button htmlType="submit" onClick={goback}>
                            返回
                        </Button>
                    </div>
                </Form>
            </div>
        </div>

    </div>
}
export default Mod_memberinterests